/*
 * Copyright (c) 2020 Huawei Technologies Co.,Ltd.
 *
 * openGauss is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *
 *          http://license.coscl.org.cn/MulanPSL2
 *
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 * -------------------------------------------------------------------------
 *
 * vl_utils.cpp
 *    Variable-length row help functions
 *
 * IDENTIFICATION
 *    src/gausskernel/storage/mot/core/storage/vl_utils.cpp
 *
 * -------------------------------------------------------------------------
 */

#include <map>
#include "row.h"
#include "vl_utils.h"

namespace MOT {

    uint32_t CalcDatumToMOTSize(MOT::Column* col, Datum datum, Oid type, bool isnull, uint32_t &extSize)
    {
        uint32_t colSize = 0;
        extSize = 0;
        if (isVariableLengthMotType(col->m_type)) {
            MOT_ASSERT(isVariableLengthPgType(type));
            colSize = sizeof(MOT::VlColumnHdr_t);
            if (!isnull) {
                bytea* txt = DatumGetByteaP(datum);
                size_t size = VARSIZE(txt);  // includes header len VARHDRSZ
                extSize = size - VARHDRSZ;
            }
        } else {
            // Variable-length header is not required
            colSize = col->m_size;
        }

        return colSize;
    }

    bool isVariableLengthPgType(Oid type) {
        bool res = false;
        switch (type) {
            case BYTEAOID:
            case TEXTOID:
            case VARCHAROID:
            case NVARCHAR2OID:
            case BPCHAROID:
            case CLOBOID:
                res = true;
                break;

            default:
                res = false;
                break;
        }

        return res;
    }

    bool isVariableLengthMotType(MOT::MOT_CATALOG_FIELD_TYPES type) {
        if (type == MOT::MOT_CATALOG_FIELD_TYPES::MOT_TYPE_HTAPBLOB) {
            return true;
        }

        return false;
    }

};  // namespace MOT
